package com.zn.web.controler;


import com.alibaba.fastjson.JSONObject;
import com.zn.entity.ContractAnalysis;
import com.zn.entity.MarketTradeDetail;
import com.zn.entity.OptionMarketDataField;
import com.zn.service.MdInfoService;
import com.zn.util.Constant;
import com.zn.vo.EtfMdInfo;
import com.zn.vo.Message;
import com.zn.vo.OptionSymbol;
import com.zn.web.dto.KLineDto;
import com.zn.web.rpc.MdRemoteCall;
import com.zn.web.vo.TradingVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mdInfo")
public class MdInfoController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MdInfoController.class);
    @Autowired
    private MdInfoService mdInfoService;
    @Autowired
    private MdRemoteCall mdRemoteCall;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 进入APP第一次获取数据
     * @return
     */
    @RequestMapping(value = "/getTargetList",method = RequestMethod.POST)
    public ResponseEntity<Message> getTargetList() {
        try {
            Map<String, List<?>> map = mdInfoService.getTargetList();
            return ResponseEntity.ok(Message.successData(map));
        }catch (Exception ex){
            LOGGER.error("getTargetList........."+ex);
        }
        return ResponseEntity.ok(Message.SYS_ERROR);
    }

    /**
     * 根据条件查询首页数据
     * @param record
     * @return
     */
    @RequestMapping(value = "/findTargetList",method = RequestMethod.POST)
    public ResponseEntity<Message> findTargetList(@RequestBody TradingVo record) {
        try {
            if (StringUtils.isBlank(record.getTradingGoodsCode())){
                return ResponseEntity.ok(Message.ARGS_ERROR);
            }
            Map<String, List<?>> map = mdInfoService.findTargetList(record);
            return ResponseEntity.ok(Message.successData(map));
        }catch (Exception ex){
            LOGGER.error("findTargetList........."+ex);
        }
        return ResponseEntity.ok(Message.SYS_ERROR);
    }


    /**
     * 获取行情初始化数据
     * @param record
     * @return
     */
    @RequestMapping(value = "/getQuotation",method = RequestMethod.POST)
    public ResponseEntity<Message> getQuotation(@RequestBody TradingVo record) {
        try {
            if (StringUtils.isBlank(record.getInstrumentCode())){
                return ResponseEntity.ok(Message.ARGS_ERROR);
            }
            Object minLine = mdInfoService.getSinaMinLine(record);
            return ResponseEntity.ok(Message.successData(minLine));
        }catch (Exception ex){
            LOGGER.error("getQuotation........."+ex);
        }
        return ResponseEntity.ok(Message.SYS_ERROR);
    }

    /**
     * 获取所有合约名称信息
     * @return
     */
    @RequestMapping(value = "/getContractList",method = RequestMethod.POST)
    public ResponseEntity<Message> getContractList() {
        try {
            List<OptionSymbol> optionSymbolList = mdInfoService.getContractList();
            return ResponseEntity.ok(Message.successData(optionSymbolList));
        }catch (Exception ex){
            LOGGER.error("getContractList........."+ex);
        }
        return ResponseEntity.ok(Message.SYS_ERROR);
    }

    /**
     * 根据合约ID查询合约信息
     * @param record
     * @return
     */
    @RequestMapping(value = "/findContract",method = RequestMethod.POST)
    public ResponseEntity<Message> findContract(@RequestBody TradingVo record) {
        try {
            if (StringUtils.isBlank(record.getInstrumentCode())){
                return ResponseEntity.ok(Message.ARGS_ERROR);
            }
            OptionMarketDataField optionMarketDataField = mdInfoService.getTargetContract(record);
            if(optionMarketDataField==null){
                return ResponseEntity.ok(Message.CONTRACT_ARGS_ERROR);
            }else{
                return ResponseEntity.ok(Message.successData(optionMarketDataField));
            }
        }catch (Exception ex){
            LOGGER.error("findContract........."+ex);
            return ResponseEntity.ok(Message.SYS_ERROR);
        }
    }

    /**
     * 获取交易品的合约K线
     * @return
     */
    @RequestMapping(value = "/getContractKLine",method = RequestMethod.POST)
    public ResponseEntity<Message> getContractKLine(@RequestBody KLineDto kLineDto) {
        try{
            LOGGER.info("begin......................" + kLineDto.toString());
            Map<String,Object> kLineEntityMap=mdInfoService.getKLineList(kLineDto);
            return ResponseEntity.ok(Message.successData(kLineEntityMap));
        }catch (Exception e){
            LOGGER.error("getContractKLine...",e);
            return ResponseEntity.ok(Message.SYS_ERROR);
        }
    }


    /**
     * 获取合约分析（详情接口）
     * @return
     */
    @RequestMapping(value = "/getContractAnalysis",method = RequestMethod.POST)
    public ResponseEntity<Message> getContractAnalysis(@RequestBody TradingVo tradingVo) {
        try{
            LOGGER.info("getContractAnalysis......................" + tradingVo.toString());
            ContractAnalysis contractAnalysis=mdRemoteCall.getContractAnalysis(tradingVo.getInstrumentCode());
            return ResponseEntity.ok(Message.successData(contractAnalysis));
        }catch (Exception e){
            LOGGER.error("getContractAnalysis...",e);
            return ResponseEntity.ok(Message.SYS_ERROR);
        }
    }

    /**
     * 获取参考行情接口
     * @return
     */
    @RequestMapping(value = "/getReferMdInfo",method = RequestMethod.POST)
    public ResponseEntity<Message> getReferMdInfo() {
        try{
            List<Object> referMdInforList=redisTemplate.opsForHash().values(Constant.SINA_REFER_MD_LIST);
            LinkedList<EtfMdInfo> referMdInforListSort=new LinkedList<EtfMdInfo>();
            for(Object obj:referMdInforList){
                EtfMdInfo etfMdInfo= JSONObject.parseObject(obj.toString(),EtfMdInfo.class);
                if(etfMdInfo.getEtfName().startsWith("上证")){
                    referMdInforListSort.add(0,etfMdInfo);
                }else{
                    referMdInforListSort.add(etfMdInfo);
                }
            }
            return ResponseEntity.ok(Message.successData(referMdInforListSort));
        }catch (Exception e){
            LOGGER.error("getReferMdInfo...",e);
            return ResponseEntity.ok(Message.SYS_ERROR);
        }
    }

    //
    /**
     * 获取参考行情接口
     * @return
     */
    @RequestMapping(value = "/getMarketTradeDetail",method = RequestMethod.POST)
    public ResponseEntity<Message> getMarketTradeDetail(@RequestBody TradingVo tradingVo){
        try{
            List<MarketTradeDetail> marketTradeDetails=mdInfoService.getMarketTradeDetail(tradingVo);
            return ResponseEntity.ok(Message.successData(marketTradeDetails));
        }catch (Exception e){
            LOGGER.error("getReferMdInfo...",e);
            return ResponseEntity.ok(Message.SYS_ERROR);
        }
    }
}